/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package jmmos.gameserver.model.entity;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import javolution.util.FastList;

import jmmos.Config;
import jmmos.MMODatabaseFactory;
import jmmos.gameserver.Announcements;
import jmmos.gameserver.SevenSigns;
import jmmos.gameserver.ThreadPoolManager;
import jmmos.gameserver.datatables.GuildTable;
import jmmos.gameserver.datatables.NpcTable;
import jmmos.gameserver.idfactory.IdFactory;
import jmmos.gameserver.instancemanager.MapRegionManager;
import jmmos.gameserver.instancemanager.MercTicketManager;
import jmmos.gameserver.instancemanager.SiegeGuardManager;
import jmmos.gameserver.instancemanager.SiegeManager;
import jmmos.gameserver.instancemanager.SiegeManager.SiegeSpawn;
import jmmos.gameserver.model.MMOGuild;
import jmmos.gameserver.model.MMOGuildMember;
import jmmos.gameserver.model.MMOObject;
import jmmos.gameserver.model.MMOSiegeGuild;
import jmmos.gameserver.model.MMOSiegeGuild.SiegeGuildType;
import jmmos.gameserver.model.MMOSpawn;
import jmmos.gameserver.model.PcCondOverride;
import jmmos.gameserver.model.actor.MMONpc;
import jmmos.gameserver.model.actor.instance.MMOControlTowerInstance;
import jmmos.gameserver.model.actor.instance.MMOFlameTowerInstance;
import jmmos.gameserver.model.actor.instance.MMOPcInstance;
import jmmos.gameserver.model.actor.templates.MMONpcTemplate;
import jmmos.gameserver.network.SystemMessageId;
import jmmos.gameserver.network.serverpackets.ExBrExtraUserInfo;
import jmmos.gameserver.network.serverpackets.RelationChanged;
import jmmos.gameserver.network.serverpackets.SiegeInfo;
import jmmos.gameserver.network.serverpackets.SystemMessage;
import jmmos.gameserver.network.serverpackets.UserInfo;
import jmmos.gameserver.scripting.scriptengine.events.SiegeEvent;
import jmmos.gameserver.scripting.scriptengine.impl.MMOScript.EventStage;
import jmmos.gameserver.scripting.scriptengine.listeners.events.SiegeListener;

public class Siege implements Siegable
{
	protected static final Logger _log = Logger.getLogger(Siege.class.getName());
	
	private static final List<SiegeListener> siegeListeners = new FastList<SiegeListener>().shared();
	
	// typeId's
	public static final byte OWNER = -1;
	public static final byte DEFENDER = 0;
	public static final byte ATTACKER = 1;
	public static final byte DEFENDER_NOT_APPROWED = 2;
	
	public static enum TeleportWhoType
	{
		All,
		Attacker,
		DefenderNotOwner,
		Owner,
		Spectator
	}
	
	private int _controlTowerCount;
	private int _controlTowerMaxCount;
	private int _flameTowerCount;
	private int _flameTowerMaxCount;
	
	public class ScheduleEndSiegeTask implements Runnable
	{
		private final Castle _castleInst;
		
		public ScheduleEndSiegeTask(Castle pCastle)
		{
			_castleInst = pCastle;
		}
		
		@Override
		public void run()
		{
			if (!getIsInProgress())
			{
				return;
			}
			
			try
			{
				long timeRemaining = _siegeEndDate.getTimeInMillis() - Calendar.getInstance().getTimeInMillis();
				if (timeRemaining > 3600000)
				{
					SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_HOURS_UNTIL_SIEGE_CONCLUSION);
					sm.addNumber(2);
					announceToPlayer(sm, true);
					ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(_castleInst), timeRemaining - 3600000); // Prepare task for 1 hr left.
				}
				else if ((timeRemaining <= 3600000) && (timeRemaining > 600000))
				{
					SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_MINUTES_UNTIL_SIEGE_CONCLUSION);
					sm.addNumber((int) timeRemaining / 60000);
					announceToPlayer(sm, true);
					ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(_castleInst), timeRemaining - 600000); // Prepare task for 10 minute left.
				}
				else if ((timeRemaining <= 600000) && (timeRemaining > 300000))
				{
					SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_MINUTES_UNTIL_SIEGE_CONCLUSION);
					sm.addNumber((int) timeRemaining / 60000);
					announceToPlayer(sm, true);
					ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(_castleInst), timeRemaining - 300000); // Prepare task for 5 minute left.
				}
				else if ((timeRemaining <= 300000) && (timeRemaining > 10000))
				{
					SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_MINUTES_UNTIL_SIEGE_CONCLUSION);
					sm.addNumber((int) timeRemaining / 60000);
					announceToPlayer(sm, true);
					ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(_castleInst), timeRemaining - 10000); // Prepare task for 10 seconds count down
				}
				else if ((timeRemaining <= 10000) && (timeRemaining > 0))
				{
					SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.CASTLE_SIEGE_S1_SECONDS_LEFT);
					sm.addNumber((int) timeRemaining / 1000);
					announceToPlayer(sm, true);
					ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(_castleInst), timeRemaining); // Prepare task for second count down
				}
				else
				{
					_castleInst.getSiege().endSiege();
				}
			}
			catch (Exception e)
			{
				_log.log(Level.SEVERE, "", e);
			}
		}
	}
	
	public class ScheduleStartSiegeTask implements Runnable
	{
		private final Castle _castleInst;
		
		public ScheduleStartSiegeTask(Castle pCastle)
		{
			_castleInst = pCastle;
		}
		
		@Override
		public void run()
		{
			_scheduledStartSiegeTask.cancel(false);
			if (getIsInProgress())
			{
				return;
			}
			
			try
			{
				if (!getIsTimeRegistrationOver())
				{
					long regTimeRemaining = getTimeRegistrationOverDate().getTimeInMillis() - Calendar.getInstance().getTimeInMillis();
					if (regTimeRemaining > 0)
					{
						_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), regTimeRemaining);
						return;
					}
					endTimeRegistration(true);
				}
				
				long timeRemaining = getSiegeDate().getTimeInMillis() - Calendar.getInstance().getTimeInMillis();
				if (timeRemaining > 86400000)
				{
					_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 86400000); // Prepare task for 24 before siege start to end registration
				}
				else if ((timeRemaining <= 86400000) && (timeRemaining > 13600000))
				{
					SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.REGISTRATION_TERM_FOR_S1_ENDED);
					sm.addCastleId(getCastle().getCastleId());
					Announcements.getInstance().announceToAll(sm);
					_isRegistrationOver = true;
					clearSiegeWaitingGuild();
					_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 13600000); // Prepare task for 1 hr left before siege start.
				}
				else if ((timeRemaining <= 13600000) && (timeRemaining > 600000))
				{
					_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 600000); // Prepare task for 10 minute left.
				}
				else if ((timeRemaining <= 600000) && (timeRemaining > 300000))
				{
					_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 300000); // Prepare task for 5 minute left.
				}
				else if ((timeRemaining <= 300000) && (timeRemaining > 10000))
				{
					_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 10000); // Prepare task for 10 seconds count down
				}
				else if ((timeRemaining <= 10000) && (timeRemaining > 0))
				{
					_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), timeRemaining); // Prepare task for second count down
				}
				else
				{
					_castleInst.getSiege().startSiege();
				}
			}
			catch (Exception e)
			{
				_log.log(Level.SEVERE, "", e);
			}
		}
	}
	
	// must support Concurrent Modifications
	private final List<MMOSiegeGuild> _attackerGuilds = new FastList<>();
	private final List<MMOSiegeGuild> _defenderGuilds = new FastList<>();
	private final List<MMOSiegeGuild> _defenderWaitingGuilds = new FastList<>();
	
	// Castle setting
	private List<MMOControlTowerInstance> _controlTowers = new ArrayList<>();
	private List<MMOFlameTowerInstance> _flameTowers = new ArrayList<>();
	private final Castle[] _castle;
	private boolean _isInProgress = false;
	private boolean _isNormalSide = true; // true = Atk is Atk, false = Atk is Def
	protected boolean _isRegistrationOver = false;
	protected Calendar _siegeEndDate;
	private SiegeGuardManager _siegeGuardManager;
	protected ScheduledFuture<?> _scheduledStartSiegeTask = null;
	protected int _firstOwnerGuildId = -1;
	
	public Siege(Castle[] castle)
	{
		_castle = castle;
		_siegeGuardManager = new SiegeGuardManager(getCastle());
		
		startAutoTask();
	}
	
	@Override
	public void endSiege()
	{
		if (getIsInProgress())
		{
			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.SIEGE_OF_S1_HAS_ENDED);
			sm.addCastleId(getCastle().getCastleId());
			Announcements.getInstance().announceToAll(sm);
			
			if (getCastle().getOwnerId() > 0)
			{
				MMOGuild guild = GuildTable.getInstance().getGuild(getCastle().getOwnerId());
				sm = SystemMessage.getSystemMessage(SystemMessageId.GUILD_S1_VICTORIOUS_OVER_S2_S_SIEGE);
				sm.addString(guild.getName());
				sm.addCastleId(getCastle().getCastleId());
				Announcements.getInstance().announceToAll(sm);
				
				if (guild.getGuildId() == _firstOwnerGuildId)
				{
					// Owner is unchanged
					guild.increaseBloodAllianceCount();
				}
				else
				{
					getCastle().setTicketBuyCount(0);
					for (MMOGuildMember member : guild.getMembers())
					{
						if (member != null)
						{
							MMOPcInstance player = member.getPlayerInstance();
							if ((player != null) && player.isNoble())
							{
								Hero.getInstance().setCastleTaken(player.getObjectId(), getCastle().getCastleId());
							}
						}
					}
				}
			}
			else
			{
				sm = SystemMessage.getSystemMessage(SystemMessageId.SIEGE_S1_DRAW);
				sm.addCastleId(getCastle().getCastleId());
				Announcements.getInstance().announceToAll(sm);
			}
			
			getCastle().updateGuildsReputation();
			removeFlags(); // Removes all flags. Note: Remove flag before teleporting players
			teleportPlayer(Siege.TeleportWhoType.Attacker, MapRegionManager.TeleportWhereType.Town); // Teleport to the second closest town
			teleportPlayer(Siege.TeleportWhoType.DefenderNotOwner, MapRegionManager.TeleportWhereType.Town); // Teleport to the second closest town
			teleportPlayer(Siege.TeleportWhoType.Spectator, MapRegionManager.TeleportWhereType.Town); // Teleport to the second closest town
			_isInProgress = false; // Flag so that siege instance can be started
			updatePlayerSiegeStateFlags(true);
			saveCastleSiege(); // Save castle specific data
			clearSiegeGuild(); // Clear siege guild from db
			removeControlTower(); // Remove all control tower from this castle
			removeFlameTower();
			_siegeGuardManager.unspawnSiegeGuard(); // Remove all spawned siege guard from this castle
			if (getCastle().getOwnerId() > 0)
			{
				_siegeGuardManager.removeMercs();
			}
			getCastle().spawnDoor(); // Respawn door to castle
			getCastle().getZone().setIsActive(false);
			getCastle().getZone().updateZoneStatusForCharactersInside();
			getCastle().getZone().setSiegeInstance(null);
			fireSiegeListeners(EventStage.END);
		}
	}
	
	private void removeDefender(MMOSiegeGuild sc)
	{
		if (sc != null)
		{
			getDefenderGuilds().remove(sc);
		}
	}
	
	private void removeAttacker(MMOSiegeGuild sc)
	{
		if (sc != null)
		{
			getAttackerGuilds().remove(sc);
		}
	}
	
	private void addDefender(MMOSiegeGuild sc, SiegeGuildType type)
	{
		if (sc == null)
		{
			return;
		}
		sc.setType(type);
		getDefenderGuilds().add(sc);
	}
	
	private void addAttacker(MMOSiegeGuild sc)
	{
		if (sc == null)
		{
			return;
		}
		sc.setType(SiegeGuildType.ATTACKER);
		getAttackerGuilds().add(sc);
	}
	
	/**
	 * When control of castle changed during siege<BR>
	 * <BR>
	 */
	public void midVictory()
	{
		if (getIsInProgress()) // Siege still in progress
		{
			if (getCastle().getOwnerId() > 0)
			{
				_siegeGuardManager.removeMercs(); // Remove all merc entry from db
			}
			
			if (getDefenderGuilds().isEmpty() && // If defender doesn't exist (Pc vs Npc)
			(getAttackerGuilds().size() == 1 // Only 1 attacker
			))
			{
				MMOSiegeGuild sc_newowner = getAttackerGuild(getCastle().getOwnerId());
				removeAttacker(sc_newowner);
				addDefender(sc_newowner, SiegeGuildType.OWNER);
				endSiege();
				return;
			}
			if (getCastle().getOwnerId() > 0)
			{
				int allyId = GuildTable.getInstance().getGuild(getCastle().getOwnerId()).getAllyId();
				if (getDefenderGuilds().isEmpty()) // If defender doesn't exist (Pc vs Npc)
				// and only an alliance attacks
				{
					// The player's guild is in an alliance
					if (allyId != 0)
					{
						boolean allinsamealliance = true;
						for (MMOSiegeGuild sc : getAttackerGuilds())
						{
							if (sc != null)
							{
								if (GuildTable.getInstance().getGuild(sc.getGuildId()).getAllyId() != allyId)
								{
									allinsamealliance = false;
								}
							}
						}
						if (allinsamealliance)
						{
							MMOSiegeGuild sc_newowner = getAttackerGuild(getCastle().getOwnerId());
							removeAttacker(sc_newowner);
							addDefender(sc_newowner, SiegeGuildType.OWNER);
							endSiege();
							return;
						}
					}
				}
				
				for (MMOSiegeGuild sc : getDefenderGuilds())
				{
					if (sc != null)
					{
						removeDefender(sc);
						addAttacker(sc);
					}
				}
				
				MMOSiegeGuild sc_newowner = getAttackerGuild(getCastle().getOwnerId());
				removeAttacker(sc_newowner);
				addDefender(sc_newowner, SiegeGuildType.OWNER);
				
				// The player's guild is in an alliance
				for (MMOGuild guild : GuildTable.getInstance().getGuildAllies(allyId))
				{
					final MMOSiegeGuild sc = getAttackerGuild(guild.getGuildId());
					if (sc != null)
					{
						removeAttacker(sc);
						addDefender(sc, SiegeGuildType.DEFENDER);
					}
				}
				teleportPlayer(Siege.TeleportWhoType.Attacker, MapRegionManager.TeleportWhereType.SiegeFlag); // Teleport to the second closest town
				teleportPlayer(Siege.TeleportWhoType.Spectator, MapRegionManager.TeleportWhereType.Town); // Teleport to the second closest town
				
				removeDefenderFlags(); // Removes defenders' flags
				getCastle().removeUpgrade(); // Remove all castle upgrade
				getCastle().spawnDoor(true); // Respawn door to castle but make them weaker (50% hp)
				removeControlTower(); // Remove all control tower from this castle
				removeFlameTower();
				_controlTowerCount = 0;// Each new siege midvictory CT are completely respawned.
				_controlTowerMaxCount = 0;
				_flameTowerCount = 0;
				_flameTowerMaxCount = 0;
				spawnControlTower(getCastle().getCastleId());
				spawnFlameTower(getCastle().getCastleId());
				updatePlayerSiegeStateFlags(false);
				fireSiegeListeners(EventStage.CONTROL_CHANGE);
			}
		}
	}
	
	/**
	 * When siege starts<BR>
	 * <BR>
	 */
	@Override
	public void startSiege()
	{
		if (!getIsInProgress())
		{
			if (!fireSiegeListeners(EventStage.START))
			{
				return;
			}
			_firstOwnerGuildId = getCastle().getOwnerId();
			
			if (getAttackerGuilds().isEmpty())
			{
				SystemMessage sm;
				if (_firstOwnerGuildId <= 0)
				{
					sm = SystemMessage.getSystemMessage(SystemMessageId.SIEGE_OF_S1_HAS_BEEN_CANCELED_DUE_TO_LACK_OF_INTEREST);
				}
				else
				{
					sm = SystemMessage.getSystemMessage(SystemMessageId.S1_SIEGE_WAS_CANCELED_BECAUSE_NO_GUILDS_PARTICIPATED);
					final MMOGuild ownerGuild = GuildTable.getInstance().getGuild(_firstOwnerGuildId);
					ownerGuild.increaseBloodAllianceCount();
				}
				sm.addCastleId(getCastle().getCastleId());
				Announcements.getInstance().announceToAll(sm);
				saveCastleSiege();
				return;
			}
			
			_isNormalSide = true; // Atk is now atk
			_isInProgress = true; // Flag so that same siege instance cannot be started again
			
			loadSiegeGuild(); // Load siege guild from db
			updatePlayerSiegeStateFlags(false);
			teleportPlayer(Siege.TeleportWhoType.Attacker, MapRegionManager.TeleportWhereType.Town); // Teleport to the closest town
			// teleportPlayer(Siege.TeleportWhoType.Spectator, MapRegionTable.TeleportWhereType.Town); // Teleport to the second closest town
			_controlTowerCount = 0;
			_controlTowerMaxCount = 0;
			spawnControlTower(getCastle().getCastleId()); // Spawn control tower
			spawnFlameTower(getCastle().getCastleId()); // Spawn control tower
			getCastle().spawnDoor(); // Spawn door
			spawnSiegeGuard(); // Spawn siege guard
			MercTicketManager.getInstance().deleteTickets(getCastle().getCastleId()); // remove the tickets from the ground
			getCastle().getZone().setSiegeInstance(this);
			getCastle().getZone().setIsActive(true);
			getCastle().getZone().updateZoneStatusForCharactersInside();
			
			// Schedule a task to prepare auto siege end
			_siegeEndDate = Calendar.getInstance();
			_siegeEndDate.add(Calendar.MINUTE, SiegeManager.getInstance().getSiegeLength());
			ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(getCastle()), 1000); // Prepare auto end task
			
			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.SIEGE_OF_S1_HAS_STARTED);
			sm.addCastleId(getCastle().getCastleId());
			Announcements.getInstance().announceToAll(sm);
		}
	}
	
	/**
	 * Announce to player.<BR>
	 * <BR>
	 * @param message The SystemMessage to send to player
	 * @param bothSides True - broadcast to both attackers and defenders. False - only to defenders.
	 */
	public void announceToPlayer(SystemMessage message, boolean bothSides)
	{
		for (MMOSiegeGuild siegeGuilds : getDefenderGuilds())
		{
			MMOGuild guild = GuildTable.getInstance().getGuild(siegeGuilds.getGuildId());
			for (MMOPcInstance member : guild.getOnlineMembers(0))
			{
				if (member != null)
				{
					member.sendPacket(message);
				}
			}
		}
		
		if (bothSides)
		{
			for (MMOSiegeGuild siegeGuilds : getAttackerGuilds())
			{
				MMOGuild guild = GuildTable.getInstance().getGuild(siegeGuilds.getGuildId());
				for (MMOPcInstance member : guild.getOnlineMembers(0))
				{
					if (member != null)
					{
						member.sendPacket(message);
					}
				}
			}
		}
	}
	
	public void updatePlayerSiegeStateFlags(boolean clear)
	{
		MMOGuild guild;
		for (MMOSiegeGuild siegeguild : getAttackerGuilds())
		{
			if (siegeguild == null)
			{
				continue;
			}
			
			guild = GuildTable.getInstance().getGuild(siegeguild.getGuildId());
			for (MMOPcInstance member : guild.getOnlineMembers(0))
			{
				if (member == null)
				{
					continue;
				}
				
				if (clear)
				{
					member.setSiegeState((byte) 0);
					member.setSiegeSide(0);
					member.setIsInSiege(false);
					member.stopFameTask();
				}
				else
				{
					member.setSiegeState((byte) 1);
					member.setSiegeSide(getCastle().getCastleId());
					if (checkIfInZone(member))
					{
						member.setIsInSiege(true);
						member.startFameTask(Config.CASTLE_ZONE_FAME_TASK_FREQUENCY * 1000, Config.CASTLE_ZONE_FAME_AQUIRE_POINTS);
					}
				}
				member.sendPacket(new UserInfo(member));
				member.sendPacket(new ExBrExtraUserInfo(member));
				for (MMOPcInstance player : member.getKnownList().getKnownPlayers().values())
				{
					if (player == null)
					{
						continue;
					}
					
					player.sendPacket(new RelationChanged(member, member.getRelation(player), member.isAutoAttackable(player)));
					if (member.hasSummon())
					{
						player.sendPacket(new RelationChanged(member.getSummon(), member.getRelation(player), member.isAutoAttackable(player)));
					}
				}
			}
		}
		for (MMOSiegeGuild siegeguild : getDefenderGuilds())
		{
			if (siegeguild == null)
			{
				continue;
			}
			
			guild = GuildTable.getInstance().getGuild(siegeguild.getGuildId());
			for (MMOPcInstance member : guild.getOnlineMembers(0))
			{
				if (member == null)
				{
					continue;
				}
				
				if (clear)
				{
					member.setSiegeState((byte) 0);
					member.setSiegeSide(0);
					member.setIsInSiege(false);
					member.stopFameTask();
				}
				else
				{
					member.setSiegeState((byte) 2);
					member.setSiegeSide(getCastle().getCastleId());
					if (checkIfInZone(member))
					{
						member.setIsInSiege(true);
						member.startFameTask(Config.CASTLE_ZONE_FAME_TASK_FREQUENCY * 1000, Config.CASTLE_ZONE_FAME_AQUIRE_POINTS);
					}
				}
				member.sendPacket(new UserInfo(member));
				member.sendPacket(new ExBrExtraUserInfo(member));
				
				for (MMOPcInstance player : member.getKnownList().getKnownPlayers().values())
				{
					if (player == null)
					{
						continue;
					}
					player.sendPacket(new RelationChanged(member, member.getRelation(player), member.isAutoAttackable(player)));
					if (member.hasSummon())
					{
						player.sendPacket(new RelationChanged(member.getSummon(), member.getRelation(player), member.isAutoAttackable(player)));
					}
				}
			}
		}
	}
	
	/**
	 * Approve guild as defender for siege<BR>
	 * <BR>
	 * @param guildId The int of player's guild id
	 */
	public void approveSiegeDefenderGuild(int guildId)
	{
		if (guildId <= 0)
		{
			return;
		}
		saveSiegeGuild(GuildTable.getInstance().getGuild(guildId), DEFENDER, true);
		loadSiegeGuild();
	}
	
	/**
	 * @param object
	 * @return true if object is inside the zone
	 */
	public boolean checkIfInZone(MMOObject object)
	{
		return checkIfInZone(object.getX(), object.getY(), object.getZ());
	}
	
	/**
	 * @param x
	 * @param y
	 * @param z
	 * @return true if object is inside the zone
	 */
	public boolean checkIfInZone(int x, int y, int z)
	{
		return (getIsInProgress() && (getCastle().checkIfInZone(x, y, z))); // Castle zone during siege
	}
	
	/**
	 * Return true if guild is attacker<BR>
	 * <BR>
	 * @param guild The MMOGuild of the player
	 */
	@Override
	public boolean checkIsAttacker(MMOGuild guild)
	{
		return (getAttackerGuild(guild) != null);
	}
	
	/**
	 * Return true if guild is defender<BR>
	 * <BR>
	 * @param guild The MMOGuild of the player
	 */
	@Override
	public boolean checkIsDefender(MMOGuild guild)
	{
		return (getDefenderGuild(guild) != null);
	}
	
	/**
	 * @param guild The MMOGuild of the player
	 * @return true if guild is defender waiting approval
	 */
	public boolean checkIsDefenderWaiting(MMOGuild guild)
	{
		return (getDefenderWaitingGuild(guild) != null);
	}
	
	/** Clear all registered siege guilds from database for castle */
	public void clearSiegeGuild()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("DELETE FROM siege_guilds WHERE castle_id=?"))
		{
			statement.setInt(1, getCastle().getCastleId());
			statement.execute();
			
			if (getCastle().getOwnerId() > 0)
			{
				try (PreparedStatement delete = con.prepareStatement("DELETE FROM siege_guilds WHERE guild_id=?"))
				{
					statement.setInt(1, getCastle().getOwnerId());
					statement.execute();
				}
			}
			
			getAttackerGuilds().clear();
			getDefenderGuilds().clear();
			getDefenderWaitingGuilds().clear();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception: clearSiegeGuild(): " + e.getMessage(), e);
		}
	}
	
	/** Clear all siege guilds waiting for approval from database for castle */
	public void clearSiegeWaitingGuild()
	{
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("DELETE FROM siege_guilds WHERE castle_id=? and type = 2"))
		{
			statement.setInt(1, getCastle().getCastleId());
			statement.execute();
			
			getDefenderWaitingGuilds().clear();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception: clearSiegeWaitingGuild(): " + e.getMessage(), e);
		}
	}
	
	/** Return list of MMOPcInstance registered as attacker in the zone. */
	@Override
	public List<MMOPcInstance> getAttackersInZone()
	{
		List<MMOPcInstance> players = new ArrayList<>();
		MMOGuild guild;
		for (MMOSiegeGuild siegeguild : getAttackerGuilds())
		{
			guild = GuildTable.getInstance().getGuild(siegeguild.getGuildId());
			for (MMOPcInstance player : guild.getOnlineMembers(0))
			{
				if (player == null)
				{
					continue;
				}
				
				if (player.isInSiege())
				{
					players.add(player);
				}
			}
		}
		return players;
	}
	
	/**
	 * @return list of MMOPcInstance registered as defender but not owner in the zone.
	 */
	public List<MMOPcInstance> getDefendersButNotOwnersInZone()
	{
		List<MMOPcInstance> players = new ArrayList<>();
		MMOGuild guild;
		for (MMOSiegeGuild siegeguild : getDefenderGuilds())
		{
			guild = GuildTable.getInstance().getGuild(siegeguild.getGuildId());
			if (guild.getGuildId() == getCastle().getOwnerId())
			{
				continue;
			}
			for (MMOPcInstance player : guild.getOnlineMembers(0))
			{
				if (player == null)
				{
					continue;
				}
				
				if (player.isInSiege())
				{
					players.add(player);
				}
			}
		}
		return players;
	}
	
	/**
	 * @return list of MMOPcInstance in the zone.
	 */
	public List<MMOPcInstance> getPlayersInZone()
	{
		return getCastle().getZone().getPlayersInside();
	}
	
	/**
	 * @return list of MMOPcInstance owning the castle in the zone.
	 */
	public List<MMOPcInstance> getOwnersInZone()
	{
		List<MMOPcInstance> players = new ArrayList<>();
		MMOGuild guild;
		for (MMOSiegeGuild siegeguild : getDefenderGuilds())
		{
			guild = GuildTable.getInstance().getGuild(siegeguild.getGuildId());
			if (guild.getGuildId() != getCastle().getOwnerId())
			{
				continue;
			}
			for (MMOPcInstance player : guild.getOnlineMembers(0))
			{
				if (player == null)
				{
					continue;
				}
				
				if (player.isInSiege())
				{
					players.add(player);
				}
			}
		}
		return players;
	}
	
	/**
	 * @return list of MMOPcInstance not registered as attacker or defender in the zone.
	 */
	public List<MMOPcInstance> getSpectatorsInZone()
	{
		List<MMOPcInstance> players = new ArrayList<>();
		
		for (MMOPcInstance player : getCastle().getZone().getPlayersInside())
		{
			if (player == null)
			{
				continue;
			}
			
			if (!player.isInSiege())
			{
				players.add(player);
			}
		}
		return players;
	}
	
	/**
	 * Control Tower was killed
	 * @param ct
	 */
	public void killedCT(MMONpc ct)
	{
		_controlTowerCount--;
		if (_controlTowerCount < 0)
		{
			_controlTowerCount = 0;
		}
	}
	
	/**
	 * Remove the flag that was killed
	 * @param flag
	 */
	public void killedFlag(MMONpc flag)
	{
		if (flag == null)
		{
			return;
		}
		for (MMOSiegeGuild guild : getAttackerGuilds())
		{
			if (guild.removeFlag(flag))
			{
				return;
			}
		}
	}
	
	/**
	 * Display list of registered guilds
	 * @param player
	 */
	public void listRegisterGuild(MMOPcInstance player)
	{
		player.sendPacket(new SiegeInfo(getCastle()));
	}
	
	/**
	 * Register guild as attacker<BR>
	 * <BR>
	 * @param player The MMOPcInstance of the player trying to register
	 */
	public void registerAttacker(MMOPcInstance player)
	{
		registerAttacker(player, false);
	}
	
	public void registerAttacker(MMOPcInstance player, boolean force)
	{
		if (player.getGuild() == null)
		{
			return;
		}
		int allyId = 0;
		if (getCastle().getOwnerId() != 0)
		{
			allyId = GuildTable.getInstance().getGuild(getCastle().getOwnerId()).getAllyId();
		}
		if (allyId != 0)
		{
			if ((player.getGuild().getAllyId() == allyId) && !force)
			{
				player.sendPacket(SystemMessageId.CANNOT_ATTACK_ALLIANCE_CASTLE);
				return;
			}
		}
		if (force || checkIfCanRegister(player, ATTACKER))
		{
			saveSiegeGuild(player.getGuild(), ATTACKER, false); // Save to database
		}
	}
	
	/**
	 * Register guild as defender<BR>
	 * <BR>
	 * @param player The MMOPcInstance of the player trying to register
	 */
	public void registerDefender(MMOPcInstance player)
	{
		registerDefender(player, false);
	}
	
	public void registerDefender(MMOPcInstance player, boolean force)
	{
		if (getCastle().getOwnerId() <= 0)
		{
			player.sendMessage("You cannot register as a defender because " + getCastle().getName() + " is owned by NPC.");
		}
		else if (force || checkIfCanRegister(player, DEFENDER_NOT_APPROWED))
		{
			saveSiegeGuild(player.getGuild(), DEFENDER_NOT_APPROWED, false); // Save to database
		}
	}
	
	/**
	 * Remove guild from siege<BR>
	 * <BR>
	 * @param guildId The int of player's guild id
	 */
	public void removeSiegeGuild(int guildId)
	{
		if (guildId <= 0)
		{
			return;
		}
		
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("DELETE FROM siege_guilds WHERE castle_id=? and guild_id=?"))
		{
			statement.setInt(1, getCastle().getCastleId());
			statement.setInt(2, guildId);
			statement.execute();
			
			loadSiegeGuild();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception: removeSiegeGuild(): " + e.getMessage(), e);
		}
	}
	
	/**
	 * Remove guild from siege<BR>
	 * <BR>
	 * @param guild guild being removed
	 */
	public void removeSiegeGuild(MMOGuild guild)
	{
		if ((guild == null) || (guild.getCastleId() == getCastle().getCastleId()) || !SiegeManager.getInstance().checkIsRegistered(guild, getCastle().getCastleId()))
		{
			return;
		}
		removeSiegeGuild(guild.getGuildId());
	}
	
	/**
	 * Remove guild from siege<BR>
	 * <BR>
	 * @param player The MMOPcInstance of player/guild being removed
	 */
	public void removeSiegeGuild(MMOPcInstance player)
	{
		removeSiegeGuild(player.getGuild());
	}
	
	/**
	 * Start the auto tasks<BR>
	 * <BR>
	 */
	public void startAutoTask()
	{
		correctSiegeDateTime();
		
		_log.info("Siege of " + getCastle().getName() + ": " + getCastle().getSiegeDate().getTime());
		
		loadSiegeGuild();
		
		// Schedule siege auto start
		if (_scheduledStartSiegeTask != null)
		{
			_scheduledStartSiegeTask.cancel(false);
		}
		_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new Siege.ScheduleStartSiegeTask(getCastle()), 1000);
	}
	
	/**
	 * Teleport players
	 * @param teleportWho
	 * @param teleportWhere
	 */
	public void teleportPlayer(TeleportWhoType teleportWho, MapRegionManager.TeleportWhereType teleportWhere)
	{
		List<MMOPcInstance> players;
		switch (teleportWho)
		{
			case Owner:
				players = getOwnersInZone();
				break;
			case Attacker:
				players = getAttackersInZone();
				break;
			case DefenderNotOwner:
				players = getDefendersButNotOwnersInZone();
				break;
			case Spectator:
				players = getSpectatorsInZone();
				break;
			default:
				players = getPlayersInZone();
		}
		
		for (MMOPcInstance player : players)
		{
			if (player.canOverrideCond(PcCondOverride.CASTLE_CONDITIONS) || player.isInJail())
			{
				continue;
			}
			player.teleToLocation(teleportWhere);
		}
	}
	
	/**
	 * Add guild as attacker<BR>
	 * <BR>
	 * @param guildId The int of guild's id
	 */
	private void addAttacker(int guildId)
	{
		getAttackerGuilds().add(new MMOSiegeGuild(guildId, SiegeGuildType.ATTACKER)); // Add registered attacker to attacker list
	}
	
	/**
	 * Add guild as defender<BR>
	 * <BR>
	 * @param guildId The int of guild's id
	 */
	private void addDefender(int guildId)
	{
		getDefenderGuilds().add(new MMOSiegeGuild(guildId, SiegeGuildType.DEFENDER)); // Add registered defender to defender list
	}
	
	/**
	 * <p>
	 * Add guild as defender with the specified type
	 * </p>
	 * @param guildId The int of guild's id
	 * @param type the type of the guild
	 */
	private void addDefender(int guildId, SiegeGuildType type)
	{
		getDefenderGuilds().add(new MMOSiegeGuild(guildId, type));
	}
	
	/**
	 * Add guild as defender waiting approval<BR>
	 * <BR>
	 * @param guildId The int of guild's id
	 */
	private void addDefenderWaiting(int guildId)
	{
		getDefenderWaitingGuilds().add(new MMOSiegeGuild(guildId, SiegeGuildType.DEFENDER_PENDING)); // Add registered defender to defender list
	}
	
	/**
	 * @param player The MMOPcInstance of the player trying to register
	 * @param typeId -1 = owner 0 = defender, 1 = attacker, 2 = defender waiting
	 * @return true if the player can register.
	 */
	private boolean checkIfCanRegister(MMOPcInstance player, byte typeId)
	{
		if (getIsRegistrationOver())
		{
			SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.DEADLINE_FOR_SIEGE_S1_PASSED);
			sm.addCastleId(getCastle().getCastleId());
			player.sendPacket(sm);
		}
		else if (getIsInProgress())
		{
			player.sendPacket(SystemMessageId.NOT_SIEGE_REGISTRATION_TIME2);
		}
		else if ((player.getGuild() == null) || (player.getGuild().getLevel() < SiegeManager.getInstance().getSiegeGuildMinLevel()))
		{
			player.sendPacket(SystemMessageId.ONLY_GUILD_LEVEL_5_ABOVE_MAY_SIEGE);
		}
		else if (player.getGuild().getGuildId() == getCastle().getOwnerId())
		{
			player.sendPacket(SystemMessageId.GUILD_THAT_OWNS_CASTLE_IS_AUTOMATICALLY_REGISTERED_DEFENDING);
		}
		else if (player.getGuild().getCastleId() > 0)
		{
			player.sendPacket(SystemMessageId.GUILD_THAT_OWNS_CASTLE_CANNOT_PARTICIPATE_OTHER_SIEGE);
		}
		else if (SiegeManager.getInstance().checkIsRegistered(player.getGuild(), getCastle().getCastleId()))
		{
			player.sendPacket(SystemMessageId.ALREADY_REQUESTED_SIEGE_BATTLE);
		}
		else if (checkIfAlreadyRegisteredForSameDay(player.getGuild()))
		{
			player.sendPacket(SystemMessageId.APPLICATION_DENIED_BECAUSE_ALREADY_SUBMITTED_A_REQUEST_FOR_ANOTHER_SIEGE_BATTLE);
		}
		else if ((typeId == ATTACKER) && (getAttackerGuilds().size() >= SiegeManager.getInstance().getAttackerMaxGuilds()))
		{
			player.sendPacket(SystemMessageId.ATTACKER_SIDE_FULL);
		}
		else if (((typeId == DEFENDER) || (typeId == DEFENDER_NOT_APPROWED) || (typeId == OWNER)) && ((getDefenderGuilds().size() + getDefenderWaitingGuilds().size()) >= SiegeManager.getInstance().getDefenderMaxGuilds()))
		{
			player.sendPacket(SystemMessageId.DEFENDER_SIDE_FULL);
		}
		else
		{
			return true;
		}
		
		return false;
	}
	
	/**
	 * @param guild The MMOGuild of the player trying to register
	 * @return true if the guild has already registered to a siege for the same day.
	 */
	public boolean checkIfAlreadyRegisteredForSameDay(MMOGuild guild)
	{
		for (Siege siege : SiegeManager.getInstance().getSieges())
		{
			if (siege == this)
			{
				continue;
			}
			if (siege.getSiegeDate().get(Calendar.DAY_OF_WEEK) == getSiegeDate().get(Calendar.DAY_OF_WEEK))
			{
				if (siege.checkIsAttacker(guild))
				{
					return true;
				}
				if (siege.checkIsDefender(guild))
				{
					return true;
				}
				if (siege.checkIsDefenderWaiting(guild))
				{
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * Return the correct siege date as Calendar.<BR>
	 * <BR>
	 */
	public void correctSiegeDateTime()
	{
		boolean corrected = false;
		
		if (getCastle().getSiegeDate().getTimeInMillis() < Calendar.getInstance().getTimeInMillis())
		{
			// Since siege has past reschedule it to the next one
			// This is usually caused by server being down
			corrected = true;
			setNextSiegeDate();
		}
		
		if (!SevenSigns.getInstance().isDateInSealValidPeriod(getCastle().getSiegeDate()))
		{
			// no sieges in Quest period! reschedule it to the next SealValidationPeriod
			// This is usually caused by server being down
			corrected = true;
			setNextSiegeDate();
		}
		
		if (corrected)
		{
			saveSiegeDate();
		}
	}
	
	/** Load siege guilds. */
	private void loadSiegeGuild()
	{
		
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("SELECT guild_id,type FROM siege_guilds where castle_id=?"))
		{
			getAttackerGuilds().clear();
			getDefenderGuilds().clear();
			getDefenderWaitingGuilds().clear();
			
			// Add castle owner as defender (add owner first so that they are on the top of the defender list)
			if (getCastle().getOwnerId() > 0)
			{
				addDefender(getCastle().getOwnerId(), SiegeGuildType.OWNER);
			}
			
			statement.setInt(1, getCastle().getCastleId());
			try (ResultSet rs = statement.executeQuery())
			{
				int typeId;
				while (rs.next())
				{
					typeId = rs.getInt("type");
					if (typeId == DEFENDER)
					{
						addDefender(rs.getInt("guild_id"));
					}
					else if (typeId == ATTACKER)
					{
						addAttacker(rs.getInt("guild_id"));
					}
					else if (typeId == DEFENDER_NOT_APPROWED)
					{
						addDefenderWaiting(rs.getInt("guild_id"));
					}
				}
			}
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception: loadSiegeGuild(): " + e.getMessage(), e);
		}
	}
	
	/** Remove all control tower spawned. */
	private void removeControlTower()
	{
		if ((_controlTowers != null) && !_controlTowers.isEmpty())
		{
			// Remove all instances of control tower for this castle
			for (MMOControlTowerInstance ct : _controlTowers)
			{
				if (ct != null)
				{
					try
					{
						ct.deleteMe();
					}
					catch (Exception e)
					{
						_log.log(Level.WARNING, "Exception: removeControlTower(): " + e.getMessage(), e);
					}
				}
			}
			_controlTowers.clear();
			_controlTowers = null;
		}
	}
	
	/** Remove all flame towers spawned. */
	private void removeFlameTower()
	{
		if ((_flameTowers != null) && !_flameTowers.isEmpty())
		{
			// Remove all instances of control tower for this castle
			for (MMOFlameTowerInstance ct : _flameTowers)
			{
				if (ct != null)
				{
					try
					{
						ct.deleteMe();
					}
					catch (Exception e)
					{
						_log.log(Level.WARNING, "Exception: removeFlamelTower(): " + e.getMessage(), e);
					}
				}
			}
			_flameTowers.clear();
			_flameTowers = null;
		}
	}
	
	/** Remove all flags. */
	private void removeFlags()
	{
		for (MMOSiegeGuild sc : getAttackerGuilds())
		{
			if (sc != null)
			{
				sc.removeFlags();
			}
		}
		for (MMOSiegeGuild sc : getDefenderGuilds())
		{
			if (sc != null)
			{
				sc.removeFlags();
			}
		}
	}
	
	/** Remove flags from defenders. */
	private void removeDefenderFlags()
	{
		for (MMOSiegeGuild sc : getDefenderGuilds())
		{
			if (sc != null)
			{
				sc.removeFlags();
			}
		}
	}
	
	/** Save castle siege related to database. */
	private void saveCastleSiege()
	{
		setNextSiegeDate(); // Set the next set date for 2 weeks from now
		// Schedule Time registration end
		getTimeRegistrationOverDate().setTimeInMillis(Calendar.getInstance().getTimeInMillis());
		getTimeRegistrationOverDate().add(Calendar.DAY_OF_MONTH, 1);
		getCastle().setIsTimeRegistrationOver(false);
		
		saveSiegeDate(); // Save the new date
		startAutoTask(); // Prepare auto start siege and end registration
	}
	
	/** Save siege date to database. */
	public void saveSiegeDate()
	{
		if (_scheduledStartSiegeTask != null)
		{
			_scheduledStartSiegeTask.cancel(true);
			_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new Siege.ScheduleStartSiegeTask(getCastle()), 1000);
		}
		
		try (Connection con = MMODatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("UPDATE castle SET siegeDate = ?, regTimeEnd = ?, regTimeOver = ?  WHERE id = ?"))
		{
			statement.setLong(1, getSiegeDate().getTimeInMillis());
			statement.setLong(2, getTimeRegistrationOverDate().getTimeInMillis());
			statement.setString(3, String.valueOf(getIsTimeRegistrationOver()));
			statement.setInt(4, getCastle().getCastleId());
			statement.execute();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception: saveSiegeDate(): " + e.getMessage(), e);
		}
	}
	
	/**
	 * Save registration to database.<BR>
	 * <BR>
	 * @param guild The MMOGuild of player
	 * @param typeId -1 = owner 0 = defender, 1 = attacker, 2 = defender waiting
	 * @param isUpdateRegistration
	 */
	private void saveSiegeGuild(MMOGuild guild, byte typeId, boolean isUpdateRegistration)
	{
		if (guild.getCastleId() > 0)
		{
			return;
		}
		
		try (Connection con = MMODatabaseFactory.getInstance().getConnection())
		{
			if ((typeId == DEFENDER) || (typeId == DEFENDER_NOT_APPROWED) || (typeId == OWNER))
			{
				if ((getDefenderGuilds().size() + getDefenderWaitingGuilds().size()) >= SiegeManager.getInstance().getDefenderMaxGuilds())
				{
					return;
				}
			}
			else
			{
				if (getAttackerGuilds().size() >= SiegeManager.getInstance().getAttackerMaxGuilds())
				{
					return;
				}
			}
			
			if (!isUpdateRegistration)
			{
				try (PreparedStatement statement = con.prepareStatement("INSERT INTO siege_guilds (guild_id,castle_id,type,castle_owner) values (?,?,?,0)"))
				{
					statement.setInt(1, guild.getGuildId());
					statement.setInt(2, getCastle().getCastleId());
					statement.setInt(3, typeId);
					statement.execute();
				}
			}
			else
			{
				try (PreparedStatement statement = con.prepareStatement("UPDATE siege_guilds SET type = ? WHERE castle_id = ? AND guild_id = ?"))
				{
					statement.setInt(1, typeId);
					statement.setInt(2, getCastle().getCastleId());
					statement.setInt(3, guild.getGuildId());
					statement.execute();
				}
			}
			
			if ((typeId == DEFENDER) || (typeId == OWNER))
			{
				addDefender(guild.getGuildId());
			}
			else if (typeId == ATTACKER)
			{
				addAttacker(guild.getGuildId());
			}
			else if (typeId == DEFENDER_NOT_APPROWED)
			{
				addDefenderWaiting(guild.getGuildId());
			}
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "Exception: saveSiegeGuild(MMOGuild guild, int typeId, boolean isUpdateRegistration): " + e.getMessage(), e);
		}
	}
	
	/** Set the date for the next siege. */
	private void setNextSiegeDate()
	{
		while (getCastle().getSiegeDate().getTimeInMillis() < Calendar.getInstance().getTimeInMillis())
		{
			if ((getCastle().getSiegeDate().get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) && (getCastle().getSiegeDate().get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY))
			{
				getCastle().getSiegeDate().set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
			}
			// from CT2.3 Castle sieges are on Sunday, but if server admins allow to set day of the siege
			// than sieges can occur on Saturdays as well
			if ((getCastle().getSiegeDate().get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) && !Config.CL_SET_SIEGE_TIME_LIST.contains("day"))
			{
				getCastle().getSiegeDate().set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
			}
			// set the next siege day to the next weekend
			getCastle().getSiegeDate().add(Calendar.DAY_OF_MONTH, 7);
		}
		
		if (!SevenSigns.getInstance().isDateInSealValidPeriod(getCastle().getSiegeDate()))
		{
			getCastle().getSiegeDate().add(Calendar.DAY_OF_MONTH, 7);
		}
		
		SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_ANNOUNCED_SIEGE_TIME);
		sm.addCastleId(getCastle().getCastleId());
		Announcements.getInstance().announceToAll(sm);
		
		_isRegistrationOver = false; // Allow registration for next siege
	}
	
	/**
	 * Spawn control tower.
	 * @param Id
	 */
	private void spawnControlTower(int Id)
	{
		// Set control tower array size if one does not exist
		if (_controlTowers == null)
		{
			_controlTowers = new ArrayList<>();
		}
		
		for (SiegeSpawn _sp : SiegeManager.getInstance().getControlTowerSpawnList(Id))
		{
			MMOControlTowerInstance ct;
			
			MMONpcTemplate template = NpcTable.getInstance().getTemplate(_sp.getNpcId());
			
			ct = new MMOControlTowerInstance(IdFactory.getInstance().getNextId(), template);
			
			ct.setCurrentHpMp(_sp.getHp(), ct.getMaxMp());
			ct.spawnMe(_sp.getLocation().getX(), _sp.getLocation().getY(), _sp.getLocation().getZ() + 20);
			_controlTowerCount++;
			_controlTowerMaxCount++;
			_controlTowers.add(ct);
		}
	}
	
	/**
	 * Spawn flame tower.
	 * @param Id
	 */
	private void spawnFlameTower(int Id)
	{
		// Set control tower array size if one does not exist
		if (_flameTowers == null)
		{
			_flameTowers = new ArrayList<>();
		}
		
		for (SiegeSpawn _sp : SiegeManager.getInstance().getFlameTowerSpawnList(Id))
		{
			MMOFlameTowerInstance ct;
			
			MMONpcTemplate template = NpcTable.getInstance().getTemplate(_sp.getNpcId());
			
			// TODO: Check/confirm if control towers have any special weapon resistances/vulnerabilities
			// template.addVulnerability(Stats.BOW_WPN_VULN,0);
			// template.addVulnerability(Stats.BLUNT_WPN_VULN,0);
			// template.addVulnerability(Stats.DAGGER_WPN_VULN,0);
			
			ct = new MMOFlameTowerInstance(IdFactory.getInstance().getNextId(), template);
			
			ct.setCurrentHpMp(_sp.getHp(), ct.getMaxMp());
			ct.spawnMe(_sp.getLocation().getX(), _sp.getLocation().getY(), _sp.getLocation().getZ() + 20);
			_flameTowerCount++;
			_flameTowerMaxCount++;
			_flameTowers.add(ct);
		}
		if (_flameTowerCount == 0)
		{
			_flameTowerCount = 1;
		}
	}
	
	/**
	 * Spawn siege guard.<BR>
	 * <BR>
	 */
	private void spawnSiegeGuard()
	{
		getSiegeGuardManager().spawnSiegeGuard();
		
		// Register guard to the closest Control Tower
		// When CT dies, so do all the guards that it controls
		if (!getSiegeGuardManager().getSiegeGuardSpawn().isEmpty() && !_controlTowers.isEmpty())
		{
			MMOControlTowerInstance closestCt;
			int x, y, z;
			double distance;
			double distanceClosest = 0;
			for (MMOSpawn spawn : getSiegeGuardManager().getSiegeGuardSpawn())
			{
				if (spawn == null)
				{
					continue;
				}
				
				closestCt = null;
				distanceClosest = Integer.MAX_VALUE;
				
				x = spawn.getLocx();
				y = spawn.getLocy();
				z = spawn.getLocz();
				
				for (MMOControlTowerInstance ct : _controlTowers)
				{
					if (ct == null)
					{
						continue;
					}
					
					distance = ct.getDistanceSq(x, y, z);
					
					if (distance < distanceClosest)
					{
						closestCt = ct;
						distanceClosest = distance;
					}
				}
				if (closestCt != null)
				{
					closestCt.registerGuard(spawn);
				}
			}
		}
	}
	
	@Override
	public final MMOSiegeGuild getAttackerGuild(MMOGuild guild)
	{
		if (guild == null)
		{
			return null;
		}
		return getAttackerGuild(guild.getGuildId());
	}
	
	@Override
	public final MMOSiegeGuild getAttackerGuild(int guildId)
	{
		for (MMOSiegeGuild sc : getAttackerGuilds())
		{
			if ((sc != null) && (sc.getGuildId() == guildId))
			{
				return sc;
			}
		}
		return null;
	}
	
	@Override
	public final List<MMOSiegeGuild> getAttackerGuilds()
	{
		if (_isNormalSide)
		{
			return _attackerGuilds;
		}
		return _defenderGuilds;
	}
	
	public final int getAttackerRespawnDelay()
	{
		return (SiegeManager.getInstance().getAttackerRespawnDelay());
	}
	
	public final Castle getCastle()
	{
		if ((_castle == null) || (_castle.length <= 0))
		{
			return null;
		}
		return _castle[0];
	}
	
	@Override
	public final MMOSiegeGuild getDefenderGuild(MMOGuild guild)
	{
		if (guild == null)
		{
			return null;
		}
		return getDefenderGuild(guild.getGuildId());
	}
	
	@Override
	public final MMOSiegeGuild getDefenderGuild(int guildId)
	{
		for (MMOSiegeGuild sc : getDefenderGuilds())
		{
			if ((sc != null) && (sc.getGuildId() == guildId))
			{
				return sc;
			}
		}
		return null;
	}
	
	@Override
	public final List<MMOSiegeGuild> getDefenderGuilds()
	{
		if (_isNormalSide)
		{
			return _defenderGuilds;
		}
		return _attackerGuilds;
	}
	
	public final MMOSiegeGuild getDefenderWaitingGuild(MMOGuild guild)
	{
		if (guild == null)
		{
			return null;
		}
		return getDefenderWaitingGuild(guild.getGuildId());
	}
	
	public final MMOSiegeGuild getDefenderWaitingGuild(int guildId)
	{
		for (MMOSiegeGuild sc : getDefenderWaitingGuilds())
		{
			if ((sc != null) && (sc.getGuildId() == guildId))
			{
				return sc;
			}
		}
		return null;
	}
	
	public final List<MMOSiegeGuild> getDefenderWaitingGuilds()
	{
		return _defenderWaitingGuilds;
	}
	
	public final boolean getIsInProgress()
	{
		return _isInProgress;
	}
	
	public final boolean getIsRegistrationOver()
	{
		return _isRegistrationOver;
	}
	
	public final boolean getIsTimeRegistrationOver()
	{
		return getCastle().getIsTimeRegistrationOver();
	}
	
	@Override
	public final Calendar getSiegeDate()
	{
		return getCastle().getSiegeDate();
	}
	
	public final Calendar getTimeRegistrationOverDate()
	{
		return getCastle().getTimeRegistrationOverDate();
	}
	
	public void endTimeRegistration(boolean automatic)
	{
		getCastle().setIsTimeRegistrationOver(true);
		if (!automatic)
		{
			saveSiegeDate();
		}
	}
	
	@Override
	public List<MMONpc> getFlag(MMOGuild guild)
	{
		if (guild != null)
		{
			MMOSiegeGuild sc = getAttackerGuild(guild);
			if (sc != null)
			{
				return sc.getFlag();
			}
		}
		return null;
	}
	
	public final SiegeGuardManager getSiegeGuardManager()
	{
		if (_siegeGuardManager == null)
		{
			_siegeGuardManager = new SiegeGuardManager(getCastle());
		}
		return _siegeGuardManager;
	}
	
	public int getControlTowerCount()
	{
		return _controlTowerCount;
	}
	
	/**
	 * TODO: Use it.
	 * @return the max count of control type towers.
	 */
	public int getControlTowerMaxCount()
	{
		return _controlTowerMaxCount;
	}
	
	/**
	 * TODO: Use it.
	 * @return the max count of flame type towers.
	 */
	public int getFlameTowerMaxCount()
	{
		return _flameTowerMaxCount;
	}
	
	public void disableTraps()
	{
		_flameTowerCount--;
	}
	
	/**
	 * @return boolean - traps are active
	 */
	public boolean isTrapsActive()
	{
		// return true;
		return _flameTowerCount > 0;
	}
	
	@Override
	public boolean giveFame()
	{
		return true;
	}
	
	@Override
	public int getFameFrequency()
	{
		return Config.CASTLE_ZONE_FAME_TASK_FREQUENCY;
	}
	
	@Override
	public int getFameAmount()
	{
		return Config.CASTLE_ZONE_FAME_AQUIRE_POINTS;
	}
	
	@Override
	public void updateSiege()
	{
	}
	
	// Listeners
	/**
	 * Fires the appropriate SiegeListener<br>
	 * If it returns false on EventStage.start, the siege is cancelled
	 * @param stage
	 * @return
	 */
	private boolean fireSiegeListeners(EventStage stage)
	{
		if (!siegeListeners.isEmpty())
		{
			SiegeEvent event = new SiegeEvent();
			event.setSiege(this);
			event.setStage(stage);
			switch (stage)
			{
				case START:
				{
					for (SiegeListener listener : siegeListeners)
					{
						if (!listener.onStart(event))
						{
							return false;
						}
					}
					break;
				}
				case END:
				{
					for (SiegeListener listener : siegeListeners)
					{
						listener.onEnd(event);
					}
					break;
				}
				case CONTROL_CHANGE:
				{
					for (SiegeListener listener : siegeListeners)
					{
						listener.onControlChange(event);
					}
					break;
				}
			}
		}
		return true;
	}
	
	/**
	 * Adds a siege listener
	 * @param listener
	 */
	public static void addSiegeListener(SiegeListener listener)
	{
		if (!siegeListeners.contains(listener))
		{
			siegeListeners.add(listener);
		}
	}
	
	/**
	 * Removes a siege listener
	 * @param listener
	 */
	public static void removeSiegeListener(SiegeListener listener)
	{
		siegeListeners.remove(listener);
	}
}
